//处理参数对象
const setParams = params => {
    let queryArr = []
    for (let key in params) {
      let str = key + '=' + params[key]
      queryArr.push(str)
    }
    return queryArr.join('&')
  }
  
//   封装Ajax
const myAjax = option =>{
    // 创建Promise对象
    const p = new Promise((resolve, reject) => {
        //   创建xhr对象
        const xhr = new XMLHttpRequest()
        //设置返回值的格式
        xhr.responseType = 'json'
        // 处理数据格式，转换层查询字符串
        const query =  setParams (option.data)
        // 判断请求方式get和post
        if (option.method.toUpperCase() === 'GET') {
            xhr.open('GET', query ? option.url + '?' +query :option.url )
            xhr.send()
        }
        else if (option.method.toUpperCase() === 'POST') {
            xhr.open('POST', option.url )
            // 设置请求头格式
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
            xhr.send(query)
        }
        xhr.onreadystatechange = function(){
            if(xhr.readyState == 4){
                if(xhr.status == 200){
                    resolve(xhr.response)
                }else {
                    reject(xhr.status)
                }
            }
        }
    })
    return p
}